package seller

import (
	"dhfshop/models/seller"
	"time"
	//"github.com/astaxie/beego"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

/*
支付时：
   1. 先校验是否有库存，没有库存不允许继续支付
   2. 有库存时，允许支付。
   3. 通过支付成功消息驱动，减少库存。
*/
type StockController struct {
	base.BaseController
}

func (this *StockController) List() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := seller.GetAllStocks(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
		r := struct {
		    TotalCount   int64     `json:"total_count"`
	        Shop    []*seller.Stock `json:"shop"`
	    }{TotalCount: cnt, Shop: l}
	    this.Data["json"] = r
	
	this.ServeJSON()
}

func (this *StockController) Post() {
	var v seller.Stock
	valid := validation.Validation{}
	this.ParseForm(&v)
	//valid.Required(v.PartnerId, "partner_id")
	//valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	shopId, err := seller.AddStock(&v)
	if err != nil {
        this.ServeError(err.Error())
		return
    }
	rsp := struct {
		ShopId    int64        `json:"shop_id"`
	    Created   time.Time    `json:"created"`
	}{ShopId: shopId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *StockController) Put() {
	v := seller.Stock{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	var updateFields []string
    if err := seller.UpdateStockById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		    ItemId     int64       `json:"partner_id"`
	        Modified   time.Time   `json:"modified"`
	    }{ItemId:v.ItemId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *StockController) Delete() {
	item_id, _ := this.GetInt("item_id")
	if err := seller.DeleteStock(int64(item_id)); err == nil {
		rsp := struct {
		    ItemId     int       `json:"item_id"`
	        Modified   time.Time   `json:"modified"`
	    }{ItemId:item_id, Modified:time.Now().UTC()}
	    this.Data["json"] = rsp
	} else {
	    this.ServeError(err.Error())
	    return
	}
	this.ServeJSON()
}


